package com.morningyet.bug.log4j2.application.interceptor;

import com.morningyet.bug.log4j2.application.cache.CaffeineTemplate;
import com.morningyet.bug.log4j2.application.constant.UserConstant;
import com.morningyet.bug.log4j2.application.controller.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 登录拦截器
 *
 * @author moringyet
 */
public class AuthInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    private final CaffeineTemplate<String, UserVO> caffeineTemplate;

    public AuthInterceptor(CaffeineTemplate<String, UserVO> caffeineTemplate) {
        this.caffeineTemplate = caffeineTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        logger.info("request-url:{}", request.getRequestURI());

        try {
            String token = request.getHeader(UserConstant.AUTH_TOKEN);
            if(Objects.isNull(token) || token.isEmpty()) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            UserVO user = caffeineTemplate.get(token);

            if(Objects.isNull(user) || Objects.isNull(user.getAct()) || user.getAct().isEmpty()) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }

            return true;
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return false;
        }

    }

}
